package com.prashantdctm.paidemail;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.gae.GAEUtils;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlImage;
import com.gargoylesoftware.htmlunit.html.HtmlImageInput;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.prashantdctm.utils.EmailUtil;
import com.prashantdctm.utils.GeneralUtil;
import com.prashantdctm.utils.HttpUtil;

public class SendEarningsServlet extends GaeHttpServlet {
	private static final Logger log = Logger.getLogger(SendEarningsServlet.class.getName());
	
	public static void main(String[] args) throws Exception {
		SendEarningsServlet p = new SendEarningsServlet();webClient = HttpUtil.getWebClient();
		
		start("pk.paidemails@gmail.com", "pk_995");
		//orkut();
		
	}
	public static void orkut() throws Exception {
		HtmlPage page = webClient.getPage("http://www.orkut.com");
		((HtmlInput) page.getElementByName("Email")).setValueAttribute("poonamdub@gmail.com");
		((HtmlInput) page.getElementByName("Passwd")).setValueAttribute("prashant");
		page = ((HtmlInput) page.getElementByName("signIn")).click();
		//System.out.println(page);
		page = webClient.getPage("http://www.orkut.com/Main#Album?uid=14601908359545768310&aid=1304982241");
		customLog("loading");
		GeneralUtil.dumpPage(page);
		
		
	}
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		super.doGet(req, resp);
		if(!isCron) {return;}
		
		stopWatch.reset();
		stopWatch.start();
		if(req.getParameter("user")!=null) {
			customLog("User = "+req.getParameter("user"));
		}
		
		try {
			start("pk.paidemails@gmail.com", "pk_995");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		stopWatch.stop();
		customLog("Time taken: " + stopWatch.toString());
		resp.getWriter().println(messageLog.toString());
		if (GAEUtils.isGaeMode()) {
			EmailUtil.sendEmail(messageLog.toString(), "sd");
		}
	}

	public static void start(String username, String pwd) throws Exception {
		HtmlPage page = null;

		try {
			page = webClient.getPage("http://www.sendearnings.com");
			
			customLog("Logging in sendearnings as " + username);
			webClient.waitForBackgroundJavaScript(5000);
			
			for (HtmlForm form : page.getForms()) {
				if (form.getAttribute("action").equals("/members/login")) {
					form.getInputByName("data[Member][username]")
							.setValueAttribute(username);
					form.getInputByName("data[Member][password]")
							.setValueAttribute(pwd);
					try{
						HtmlImageInput imgInput = form.getInputByName("submit");
						page = (HtmlPage) imgInput.click();
					} catch (Exception tempException) {
						
					}
					try{
						HtmlImageInput imgInput = form.getInputByName("submit2");
						page = (HtmlPage) imgInput.click();
					} catch (Exception tempException) {
						
					}
					break;
				}
			}
		} catch (Exception e) {
			customException("Error in logging ", e);
			e.printStackTrace();
			return;
		}
		
		page = webClient.getPage("http://www.sendearnings.com/mailbox");
		
		webClient.waitForBackgroundJavaScript(5000);
		//customLog(page.asXml());
		earningBefore = checkInboxDollars();
		customLog("Checking current earning: " + earningBefore);
		

		customLog("Landed into inbox page, processing messages");
		// customLog(page.asXml());
		HtmlAnchor anchor = null;
		while (messagesRead < 10) {

			// check if message exists
			if ((anchor = HttpUtil.getAnchorContains(page, "members/email/")) != null) {
				messagesRead++;
				String messageId = anchor.getParentNode().getPreviousSibling()
						.getPreviousSibling().getFirstChild().getAttributes()
						.getNamedItem("value").getNodeValue();
				String subject = anchor.getFirstChild().getTextContent();
				String date = anchor.getParentNode().getNextSibling()
						.getTextContent();
				customLog("MessageId: " + messageId + " | Subject: " + subject
						+ " | Date: " + date);
				if (subject.startsWith("Survey Notification") || subject.startsWith("PaidEmail - Survey")) {
					try {
						customLog("This is a survey page, deleting message");
						//webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME
						// );
						webClient.waitForBackgroundJavaScript(3000);
						HtmlCheckBoxInput checkbox = (HtmlCheckBoxInput) page
								.getByXPath(
										"//input[@value='" + messageId + "']")
								.get(0);
						checkbox.click();
						page = page.getElementByName("delete").click();
					} catch (Exception e) {
						customLog(e.getMessage());
					}
					continue;
				}

				String advPageParams = anchor.getAttributes().getNamedItem("onclick").getNodeValue();
				String advUrl = null;
				StringTokenizer stk = new StringTokenizer(advPageParams, ",");
				if (stk.hasMoreTokens()) {
					stk.nextToken();
					advUrl = "http://www.sendearnings.com/members/emailbox/"
							+ stk.nextToken().trim() + "/"
							+ stk.nextToken().trim() + "/"
							+ stk.nextToken().replace("'", "").trim();
				}
				customLog("Formatting URL for adv page: " + advUrl);

				page = webClient.getPage(advUrl);
				// GeneralUtils.dumpPage(page);
				customLog("Entering adv page");
				// webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME);
				webClient.waitForBackgroundJavaScript(3000);

				//different criteria for fetching adv href
				boolean messageSuccessfullyRead= false;
				for(HtmlAnchor anchor1: page.getAnchors()) {
					if(anchor1.getOnClickAttribute().startsWith("window.open") || anchor1.getOnClickAttribute().startsWith("showCredited")){
						anchor1.getFirstChild();
						HtmlElement img = (HtmlElement) anchor1.getFirstChild();
						customLog("Clicking image: src="+img.getAttribute("src"));
						img.click();
						Thread.sleep(5000);
						// now delete this message
						// now delete this message
						customLog("going to inbox to delete this message");
						page = webClient.getPage("http://www.sendearnings.com/mailbox");
						// webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME);
						webClient.waitForBackgroundJavaScript(3000);
						customLog("Deleting email");
						HtmlCheckBoxInput checkbox = (HtmlCheckBoxInput) page
								.getByXPath("//input[@value='" + messageId + "']")
								.get(0);
						checkbox.click();
						page = page.getElementByName("delete").click();
						messageSuccessfullyRead = true;
						break; 
					} 
				}
				if(!messageSuccessfullyRead) {
					for(HtmlAnchor anchor1: page.getAnchors()) {
						if(anchor1.getHrefAttribute().startsWith("/mail/go")){
							anchor1.click();
							Thread.sleep(5000);
							// now delete this message
							customLog("going to inbox to delete this message");
							page = webClient.getPage("http://www.sendearnings.com/mailbox");
							// webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME);
							webClient.waitForBackgroundJavaScript(3000);
							customLog("Deleting email");
							HtmlCheckBoxInput checkbox = (HtmlCheckBoxInput) page
									.getByXPath("//input[@value='" + messageId + "']")
									.get(0);
							checkbox.click();
							page = page.getElementByName("delete").click();
							messageSuccessfullyRead = true;
							break; 
						} 
					}
				}
				if(!messageSuccessfullyRead) {
					customLog("Message not read, cannot find appropriate link to click");
				}
			} else {
				//check for 'mailbox empty' label
				try{
					HtmlElement emptyElement = (HtmlElement) page.getByXPath("//div[@class='mailbox_empty']/h3/i").get(0);
					customLog(emptyElement.getTextContent());
				} catch (Exception e) {
					customException("Expecting mailbox empty message but not found", e);
				}
				
				break;
			}
		}
		earningAfter = checkInboxDollars();

		// page = HtmlUtil.getAnchorStartsWith(page, "/members/logout").click();

		customLog("Total messages read: " + messagesRead);
		customLog("Previous Earning: " + earningBefore);
		customLog("Current Earning: " + earningAfter);
		// logout
		customLog("Logging out: " + username);
		webClient.getPage("http://www.sendearnings.com/members/logout/true");
		
		webClient.closeAllWindows();
	}

	public static String checkInboxDollars() throws Exception {
		HtmlPage page = webClient.getPage("http://www.sendearnings.com/members/earnings");
		List<?> nodes = page
				.getByXPath("//tr[@class='summary']/td[text()='Total Current Earnings:']");
		if (nodes != null) {
			return ((HtmlElement) nodes.get(0)).getNextSibling()
					.getTextContent();
		}

		return null;
	}
}
